c++ 中实现"=="的重载

来源:百度知道 编辑:UC知道 时间:2024/05/21 07:04:43
我的程序如下:
#include <iostream>
#include <cstdlib>
using namespace std;
class complex{
float x,y;
public:
complex(float a = 0.0,float b = 0.0){x = a; y = b; }
complex operator==(complex op2);
};
complex complex:: operator==(complex op2)
{
if((x == op2.x)&& (y == op2.y)) return 0;
}

int main(){
complex m(2.1,3.2);
complex n(2.1,3.3);
if(m==n)
{
cout << "==" <<endl;
}
else{cout <<"!=" << endl;}
system ("PAUSE");
return 0;
}
系统不能编译,望高手指出我的错误

operator==(complex op2);
这个函数的返回值应该是bool值,好象里面的if还应该有个else。。。

你把错误信息发上来,我好看啊。。

你参考这个:
bool complex:: operator==(complex op2)
{
if((x == op2.x)&& (y == op2.y)) return 1;
//两个都相等,返回的应该是1吧
else return 0;
}

complex operator==(complex op2);
是用成员函数重载==
它必须返回指针*this(你仔细看看出错的提示)
按照你这种想法把函数头定义为:
int operator==(complex op2);
然后函数体为:
int complex:: operator==(complex op2)
{
if((x == op2.x)&& (y == op2.y)) return 1;
//从你的主函数来看此处应该为1
}
PS:wshis77的bool类型我没用过不敢保证是否正确,但是我用int没问题,还有,else可以不用